package buco.core.api;

import java.util.ArrayList;
import java.util.List;

public class ToggleWireCommand extends Command<ToggleWireParameters, ToggleWireResult>{	
	
	@Override
	public ToggleWireResult execute() throws Exception {
		BundleWire wire = getWire();  
		wire.setIsActive(!wire.isWireActive());
		
		List<IntegrityCheck> checks = IntegrityCheckRegistry.createIntegrityChecks();
		ArrayList<SemanticMessage> warnings = new ArrayList<SemanticMessage>();
		BundleIntegrityReport report = new BundleIntegrityReport();
		
		for(IntegrityCheck check : checks) {			
			check.toggleWire(wire, report); 
		}
		
		warnings.addAll(report.getMessages()); 				
		
		return new ToggleWireResult(wire, warnings);
	}
	
	private BundleWire getWire() {
		for(BundleWire wire : composition.getWires()) { 
			if(wire.getTo().getBundleID() == parameters.getToBundleID() && 
			   wire.getFrom().getBundleID() == parameters.getFromBundleID()) 
				return wire; 
		}
		return null; 
	}

	@Override
	public boolean canUndo() {	
		return true;
	}
	
	@Override
	public void undo() {
		BundleWire wire = getWire();  
		wire.setIsActive(!wire.isWireActive());
	}
	
	
}
